package com.vnp.cooking.fragmenthome;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

import com.actionbarsherlock.app.SherlockFragment;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.vnp.cooking.ApplicationContext;
import com.vnp.cooking.DangCongThucActivity;
import com.vnp.cooking.R;
import com.vnp.cooking.TaoMonAnNhapTenActivity;
import com.vnp.cooking.bean.ObjCookpad;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.KeyboardHelper;
import com.vnp.cooking.utils.PreferenceHelper;
import com.vnp.cooking.utils.Utils;

public class FrgCreateCooking extends SherlockFragment implements OnClickListener, OnEditorActionListener, OnTouchListener{
	View view;
	
	ImageButton btnBack, btnNextStep;
	EditText edtNhapten;
	// Object mon an
    ObjCookpad objCookpad = new ObjCookpad();
    ArrayList<String> tenMonAns = new ArrayList<String>();
    ArrayAdapter<String> adapter;
    PreferenceHelper preferenceHelper;
    View vFocus;
    ImageView btnClear;
    TextView txtTitle;
    private static final String SCREEN_LABEL = "Tao mon an screen";
    
    Handler mHandler = new Handler();
    Runnable r = new Runnable() {
		
		@Override
		public void run() {
			KeyboardHelper.displaySoftKeyboard(getActivity(), edtNhapten);
		}
	};
	
	View main_layout;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = (View) inflater.inflate(R.layout.activity_nhapten, container, false);
		
		preferenceHelper = new PreferenceHelper(getActivity());
		main_layout = (View) view.findViewById(R.id.main_layout);
//		KeyboardHelper.setupUI(getActivity(), main_layout);
		btnNextStep = (ImageButton) view. findViewById(R.id.btn_next_step);
		edtNhapten = (EditText) view. findViewById(R.id.edt_ten_mon);
		vFocus = (View) view.findViewById(R.id.v_focus);
		
//		showKeyboard();
//		showBoard();
		
		btnClear = (ImageView) view.findViewById(R.id.btn_clear);
		txtTitle = (TextView) view.findViewById(R.id.txt_name_cookpad_title);
		
		initFont();
		
		init();
		ApplicationContext.getGaTracker().set(Fields.SCREEN_NAME, SCREEN_LABEL);
		
		return view;
	}
	
	
	
	
	
	@Override
	public void onStart() {
		super.onStart();
//		KeyboardHelper.displaySoftKeyboard(getActivity(), edtNhapten);
		ApplicationContext.getGaTracker().send(MapBuilder.createAppView().build());
	}
	
	@Override
	public void onStop() {
		super.onStop();
//		KeyboardHelper.hideSoftKeyboard(getActivity());
	}


	void initFont() {
		txtTitle.setTypeface(Utils.getTypefaceRegular(getActivity()), Typeface.BOLD);
		edtNhapten.setTypeface(Utils.getTypefaceRegular(getActivity()));
	}
	public void init() {
		btnNextStep.setOnClickListener(this);
		btnClear.setOnClickListener(this);
		vFocus.setOnClickListener(this);
		edtNhapten.setOnTouchListener(this);
		edtNhapten.performClick();
		edtNhapten.setOnEditorActionListener(this);
		
		// xu li khi nhap ten mon an
		edtNhapten.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
		edtNhapten.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				btnClear.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if (s.toString().length() > 0) {
					
				} else {
					btnClear.setVisibility(View.GONE);
				}
			}
		});
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		edtNhapten.performClick();
		edtNhapten.setPressed(true);
		edtNhapten.invalidate();
		
		/*// Request focus and show soft keyboard automatically
		 edtNhapten.setOnFocusChangeListener(new OnFocusChangeListener() {
	            @Override
	            public void onFocusChange(View v, boolean hasFocus) {
	            	edtNhapten.post(new Runnable() {
	                    @Override
	                    public void run() {
	                        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
	                        imm.showSoftInput(edtNhapten, InputMethodManager.SHOW_IMPLICIT);
	                    }
	                });
	            }
	        });
		 edtNhapten.requestFocus();*/
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_next_step:
			KeyboardHelper.hideSoftKeyboard(getActivity());
//			vFocus.setVisibility(View.GONE);
			checkNextStep();
			break;
		case R.id.btn_clear:
			edtNhapten.setText("");
			break;
		case R.id.v_focus:
//			vFocus.setVisibility(View.GONE);
			KeyboardHelper.hideSoftKeyboard(getActivity());
			break;
		default:
			break;
		}
		
	}
	
	// create data fix filter
	public ArrayList<String> createData() {
		return tenMonAns;
	}
	
	// check buoc di buoc tiep theo
	public void checkNextStep() {
		if (TextUtils.isEmpty(edtNhapten.getText().toString())) {
			Toast.makeText(getActivity(), "Bạn chưa nhập tên món ăn", Toast.LENGTH_SHORT).show();
		} else {
			objCookpad.setNameCookpad(Utils.toOnlyFirstUpcase(edtNhapten.getText().toString()));
			Thread th = new Thread(){

				@Override
				public void run() {
					createTaomoi();
				}
				
			};
			th.start();
			gotoDangCongthuc();
		}
	}
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId == EditorInfo.IME_ACTION_NEXT) {
			KeyboardHelper.hideSoftKeyboard(getActivity());
//			vFocus.setVisibility(View.GONE);
			checkNextStep();
		}
		return true;
	}
	
	// tao cong thuc moi chua co thong tin
	public void createTaomoi(){
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					if (status == 200) {
						JSONObject data = re.getJSONObject("data");
						String recipeId = data.getString("recipe_id");
						objCookpad.setId(recipeId);
						preferenceHelper.setRecipeId(recipeId);
						Log.i("DATA", "RECIPE DATA: "+data.toString());
						Log.i("DATA", "RECIPE SAVE: "+preferenceHelper.getRecipeId());
						
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
		});
		httpClientHelper.getCreateCT(preferenceHelper.getID());
	}
	
	void showKeyboard() {
		Runnable r = new Runnable() {
			
			@Override
			public void run() {
				KeyboardHelper.displaySoftKeyboard(getActivity(), edtNhapten);
			}
		};
		mHandler.postDelayed(r, 1000);
	}
	
	
	void showBoard () {
		edtNhapten.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					 //open keyboard
	                ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(v,
	                        InputMethodManager.SHOW_FORCED);
				} else {
					
				}
			}
		});
	}
	void gotoDangCt() {
		Intent t = new Intent(getActivity(), DangCongThucActivity.class);
		t.putExtra("objCookpad", objCookpad);
//		vFocus.setVisibility(View.GONE);
		startActivity(t);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.edt_ten_mon:
//			vFocus.setVisibility(View.VISIBLE);
			break;

		default:
			break;
		}
		return false;
	}

	@Override
	public void onResume() {
		super.onResume();
//		vFocus.setVisibility(View.GONE);
	}
	
	void gotoDangCongthuc() {
		// sang trang moi
		// truyen du lieu tu ben chup anh sang
		Intent t = new Intent(getActivity(), DangCongThucActivity.class);
		t.putExtra("objCookpad", objCookpad);
		startActivity(t);
		getActivity().overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}

	
	
}
